import axios from 'axios';
import { API_ROOT } from '../config.jsx';

export const POST_VOTE = 'POST_VOTE';
export const FETCH_DETAIL = 'FETCH_DETAIL';
export const POST_COMMENT = 'POST_COMMENT';
export const POST_SURVEY = 'POST_SURVEY';
export const INIT_ARTICLE_DATA = 'INIT_ARTICLE_DATA';

export function fetchDetail(articleId) {
    axios.defaults.headers.common['Authorization'] = sessionStorage.token;
    const article = axios.get(`${API_ROOT}/wechatapi/article/${articleId}`);
    return {
        type: FETCH_DETAIL,
        payload: article
    };
}

export function postVote(articleId, callback) {
    axios.defaults.headers.common['Authorization'] = sessionStorage.token;
    const result = axios.post(`${API_ROOT}/wechatapi/vote/${articleId}`);
    result.then(function(data){
        callback(0);
    }).catch(function(error){
        callback(1);
    });
    return {
        type: POST_VOTE,
        payload: result
    };
}

export function postComment(articleId, comment, callback) {
    axios.defaults.headers.common['Authorization'] = sessionStorage.token;
    const result = axios.post(`${API_ROOT}/wechatapi/comment/${articleId}`, {
        Comment: comment
    });
    result.then(function(data){
        callback(0);
    }).catch(function(error){
        callback(1);
    });
    return {
        type: POST_COMMENT,
        payload: result
    }
}

export function postSurvey(articleId, survey, callback) {
    axios.defaults.headers.common['Authorization'] = sessionStorage.token;
    const result = axios.post(`${API_ROOT}/wechatapi/survey/${articleId}`, survey);
    result.then(function(data){
        callback(0);
    }).catch(function(error){
        callback(1);
    });
    return {
        type: POST_SURVEY,
        payload: result
    };
}

export function initArticle() {
    return {
        type: INIT_ARTICLE_DATA,
        payload: {}
    };
}